from flask import g, request, session
from sqlalchemy import or_

from app import db
from app.api_v1 import api
from app.api_v1.auth import login_required
from app.models import User, Vehicle, Preference
from libs.error_code import Success, LoginError

@api.route('/user/details', methods=['POST'])
@login_required
def get_user_details():
    """
    """
    user = User.query.filter(User.id ==g.user_id ).first()
    vehicle = Vehicle.query.filter(Vehicle.user_id ==g.user_id ).first()
    preference = Preference.query.filter(Preference.user_id ==g.user_id ).first()
    data = {
        "user":user.to_json() if user else {}, 
        "vehicle": vehicle.to_json() if vehicle else {}, 
        "preference":preference.to_json()if preference else {} 
    }
    return Success(data=data)

@api.route('/user/setinfo', methods=['POST'])
@login_required
def set_user_info():
    """
    """
    data = request.json
    return User.model_update_user_info(data)

@api.route('/vehicle/setinfo', methods=['POST'])
@login_required
def set_vehicle_info():
    """
    """
    data = request.json
    return Vehicle.model_update_vehicle_info(data)

@api.route('/preference/setinfo', methods=['POST'])
@login_required
def set_preference_info():
    """
    """
    data = request.json
    return Preference.model_update_preference_info(data)

@api.route('/user/login', methods=['POST'])
def user_login():
    """
    """
    data = request.json
    print("/user/login data ", data)
    user = User.login_verify(data)
    if user:
        session['user_id'] = user.id
        user.login_status = True
        data = user.to_json()
        return Success(data=data)
    else:
        return LoginError(message="用户不存在")

@api.route('/user/logout', methods=['POST'])
def user_logout():
    """
    """
    if session.get('user_id') is not None:
        user = User.query.filter(User.id == session.get('user_id')).first()
        if user:
            user.login_status = False
        session['user_id'] = None
    return Success(message="登出成功")

